<template>
  <div>
    <el-collapse-transition>
      <div>
        <!--顶部-->
        <div class="top">
          <div class="app-main-top-box">
            <div class="title">自定义表单</div>
            <el-button
              type="info"
              plain
              @click="addText(0, 'add')"
            >创建表单</el-button>
          </div>
        </div>
        <!--内容-->
        <div class="content">
          <div class="content app-main-content-box">
            <!--筛选-->
            <div class="filter-container">
              <el-form
                ref="filterForm"
                :inline="true"
                :model="filterForm"
                label-width="150px"
                size="small"
              >
                <el-form-item prop="title">
                  <el-input
                    v-model="filterForm.title"
                    placeholder="请输入表单标题"
                  />
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" prop="status">
                  <el-select
                    v-model="filterForm.status"
                    placeholder="请选择发布状态"
                  >
                    <el-option label="全部" value="all" />
                    <el-option label="未启用" :value="0" />
                    <el-option label="已启用" :value="1" />
                  </el-select>
                </el-form-item>
                <el-form-item label="创建时间" prop="timing">
                  <el-date-picker
                    v-model="filterForm.timing"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="最早创建"
                    end-placeholder="最晚创建"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="search">搜索</el-button>
                  <el-button @click="reset">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
            <el-table
              :data="tableData"
              border
              style="width: 100%"
              element-loading-text="加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.6)"
            >
              <el-table-column prop="title" label="标题" align="center" fixed />
              <el-table-column
                prop="desc"
                label="活动描述"
                width="650"
                align="center"
              />
              <el-table-column
                prop="createTime"
                label="创建时间"
                width="300"
                align="center"
              />
              <el-table-column
                prop="status"
                label="状态"
                width="100"
                align="center"
              >
                <template slot-scope="scope">
                  <span>{{
                    scope.row.status === 1 ? "已启用" : "未启用"
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="450">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    prop="status"
                    @click="handleStatus(scope.row)"
                  >
                    {{ scope.row.status === 0 ? "启用" : "禁用" }}
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    :disabled="scope.row.status === 0"
                    @click="shareCode(scope.row, 'share')"
                  >分享</el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="editText(scope.row, 'edit')"
                  >编辑</el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="copyText(scope.row, 'copy')"
                  >复制</el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="ClickDelete(scope.$index, scope.row)"
                  >删除</el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="goFormViewData(scope.row, 'read')"
                  >查看数据</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--分页器-->
            <pagination-direction
              v-if="paginationConfig.total !== 0"
              :config="paginationConfig"
              @sizeschange="sizesChange"
              @pagechange="pageChange"
            />

            <!-- 分享弹窗 -->
            <haibao
              ref="haibao"
              v-model="ruleForms"
              :temp-page-data="tempPageData"
              @close="closeHaiBao"
              @reload="initData()"
            />
          </div>
        </div>
      </div>
    </el-collapse-transition>
  </div>
</template>

<script>
import {
  lowCodePageList,
  CopylowCodePage,
  getH5ShareQRcode,
  updateStatus
} from '@/api/marketing'
import { mapGetters } from 'vuex'
import haibao from './components/haibao.vue'
export default {
  components: {
    haibao
  },
  data() {
    return {
      /* 筛选查询条件*/
      filterForm: {
        status: '',
        title: '',
        region: '',
        timing: ''
      },
      /* 表格内容*/
      form: {
        title: '',
        name: '',
        desc: '',
        updateTime: '',
        status: null
      },
      ruleForms: {
        dialogVisible: false
      },
      /* 分页 */
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      images: '',
      items: '',
      obj: '',
      tableData: [],
      page_id: '',
      tempPageData: {}, // 临时数据
      /* 分享打开的表单*/
      dialogFormVisible: false,
      formLabelWidth: '350px',
      /* 图片上传*/
      imageUrl: '',
      imgUrl: '',
      /* 链接*/
      link: '', // 输入框默认链接
      posterShow: false
    }
  },
  mounted() {
    // 请求表格数据
    this.initData()
  },
  computed: {
    ...mapGetters(['curMenu'])
  },
  methods: {
    /**
     * @description 请求数据
     */
    initData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.$nextTick(() => {
        this.$refs.filterForm.validate((valid, error) => {
          if (valid) {
            this.loading = true
            const params = Object.assign({}, this.filterForm)
            params.page = page
            params.pageSize = pageSize
            // 时间筛选
            params.beginTime = params.timing[0]
            params.endTime = params.timing[1]
            params.timing && delete params.timing
            // 清除多余字段
            for (const key in params) {
              if (params[key] === '' || params[key] === 'all') {
                delete params[key]
              }
            }
            lowCodePageList(params)
              .then((res) => {
                this.tableData = res.data.list
                this.paginationConfig.total = res.data.total
                this.paginationConfig.page = res.data.pageNum
              })
              .finally(() => {
                this.loading = false
              })
          }
        })
      })
    },
    /**
     * @description 搜索
     */
    search() {
      this.initData()
    },
    /**
     * @description 重置
     */
    reset() {
      this.$refs.filterForm.resetFields()
      this.initData()
    },
    /**
     * @description 启用与禁用的状态切换
     */
    handleStatus(data) {
      const params = {
        id: data.id,
        status: data.status === 0 ? 1 : 0
      }
      if (data.status === 0) {
        this.$message({
          message: '启用成功',
          type: 'success'
        })
        updateStatus(params).then((res) => {
          res.code === 0 && this.initData()
        })
      } else {
        this.$confirm('禁用后用户将无法打开表单，确定禁用?', '提示', {
          type: 'warning',
          center: true
        })
          .then((res) => {
            updateStatus(params).then((res) => {
              res.code === 0 && this.initData()
            })
          })
          .catch(() => {})
      }
    },
    /** 分享-图片上传-左
     * 获取海报图片(base64)
     * @description 根据您的需求,处理base64图片
     * @return void
     */
    shareCode(item) {
      const obj = JSON.parse(JSON.stringify(item))
      obj.pageJson = JSON.parse(obj.pageJson)
      this.tempPageData = obj
      const { posterBgImage, posterBackgroundImage, imagetext, qrCodes } = obj.pageJson
      getH5ShareQRcode({ pageId: item.id }).then((res) => {
        const form = {
          imageUrl: res.data.qrcodeUrl,
          link: res.data.qrcodeContent,
          action: res.data.copyUrl,
          posterBgImage,
          posterBackgroundImage,
          imagetext: imagetext || '您的好友邀请您参与活动，长按识别二维码。',
          qrCodes,
          qrCode: res.data.qrcodeUrl,
          dialogVisible: true
        }
        this.ruleForms = { ...form }
      })
    },
    closeHaiBao() {
      this.tempPageData = {}
      this.ruleForms.dialogVisible = false
      this.dialogVisible = false
      this.initData()
    },
    // 创建表单
    addText(page_id = 0, op) {
      this.$router.push({
        name: 'MarketingActivityCustomFormFrame',
        query: { page_id, sign: 'page-form-modal', op }
      })
    },
    // 编辑
    editText(item, op) {
      this.$nextTick(() => {
        this.curMenu[this.curMenu.length - 1] = {
          ...this.curMenu[this.curMenu.length - 1],
          title: '编辑表单'
        }
        this.$store.dispatch(
          'setCurmenu',
          JSON.parse(JSON.stringify(this.curMenu))
        )
      })
      if (op === 'edit') {
        window.localStorage.setItem('pageJson', item.pageJson),
        window.localStorage.setItem('status', item.status)
        console.log('当前状态', item.status, 'pageJson')
      }
      this.$router.push({
        name: 'MarketingActivityCustomFormFrame',
        query: { page_id: item.id, sign: 'page-form-modal', op }
      })
    },
    // 复制
    copyText(item, op) {
      this.$confirm('确定要复制该表单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          CopylowCodePage({ pageId: item.id }).then((res) => {
            this.$message({
              type: 'success',
              message: '复制成功!'
            })
          })
          if (op === 'copy') {
            window.localStorage.setItem('pageJson', item.pageJson),
            window.localStorage.setItem('status', item.status)
          }
          this.$router.push({
            name: 'MarketingActivityCustomFormFrame',
            query: { page_id: item.id, sign: 'page-form-modal', op }
          })
        })
        .catch(() => {})
    },
    // 删除
    ClickDelete(index, row) {
      this.$confirm(`删除后数据不可恢复, 是否确定继续删除?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          const data = {
            id: row.id,
            isDelete: 1
          }
          updateStatus(data).then((res) => {
            if (res.code === 0) {
              this.$message({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.initData()
            }
          })
        })
        .catch(() => {})
    },
    // 查看数据详情
    goFormViewData(item, op) {
      if (op === 'read') {
        window.localStorage.setItem('pageJson', item.pageJson)
      }
      const origin = window.location.origin
      const target = `/#/marketing/activity-customForm/components/CustomFormViewData?page_id=${item.id}&op=read`
      const url = origin + target
      console.log('打开新窗口', url)
      window.open(url)
      // this.$router.push({
      //   name: 'MarketingActivityCustomFormViewData',
      //   query: { page_id: item.id, op }
      // })
    },
    // 分页sizes改变
    sizesChange() {
      this.initData()
    },

    // 分页page改变
    pageChange() {
      this.initData()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
//头部
.top {
  padding: 24px 30px 4px;
  border-radius: 5px 5px;
  background-color: #fff;
  margin-bottom: 10px;

  .title {
    font-size: 20px;
  }
}

//内容
.content {
  padding: 0px 15px 10px;
  border-radius: 5px!important;
  background-color: #fff;
}

//筛选
.el-form {
  padding-top: 30px;

  .el-select {
    padding-left: 50px;
  }

  .el-date-editor {
    width: 400px;
  }

  .el-button {
    margin-left: 30px;
    padding: 10px 35px;
  }
}

//表格
.el-table {
  text-align: center;

  .el-button {
    padding: 0 15px 0 10px;
    font-size: small;
  }
}

//分页器
.el-pagination {
  margin-top: 50px;
}
</style>
